<script lang="ts" setup name="UploadFile">
import type { UploadChangeParam } from "ant-design-vue";
import { message, Modal } from "ant-design-vue";
import { ref } from "vue";

const props = defineProps<{
  modelValue: string; //双向绑定的文件地址
  readonly: boolean; //是否只读
}>();

const emit = defineEmits(["update:modelValue"]);

const filePath = props.modelValue;

const baseUrl = import.meta.env.VITE_API_URL;

const fileList = ref<any[]>(
  filePath
    ? [
        {
          name: filePath.split("/")?.at(-1) || "",
        },
      ]
    : []
);

const handleFileChange = (info: UploadChangeParam) => {
  if (info.file.status !== "uploading") {
    // console.log(info.file, info.fileList);
  }
  if (info.file.status === "done") {
    const url = info.file.response.data;
    // console.log(fileList);
    emit("update:modelValue", url);
    // props.modelValue["filePath"] = url;
    // message.success(`${info.file.name} file uploaded successfully`);
  } else if (info.file.status === "error") {
    message.error("上传失败");
    // message.error(`${info.file.name} file upload failed.`);
  }
};
</script>

<template>
  <a-upload
    v-if="!props.readonly"
    @change="handleFileChange"
    v-model:file-list="fileList"
    name="file"
    :action="baseUrl + '/oss/file/upload'"
  >
    <a-button v-if="!fileList.length">
      <upload-outlined></upload-outlined>
      点击上传
    </a-button>
  </a-upload>
  <a v-else :href="props.modelValue">{{ props.modelValue }}</a>
</template>

<style lang="less" scoped></style>
